package com.example.yian.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.example.yian.config.OssConfig;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/images")
public class UploadController {

    @Autowired
    private OssConfig ossConfig;
    private static final Log logger = LogFactory.getLog(UploadController.class);
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            logger.error("upload,file is empty");
            return "{\"success\": false, \"message\": \"文件为空\"}";
        }

        String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );

        try {
            PutObjectResult putObjectResult =  ossClient.putObject(new PutObjectRequest(ossConfig.getBucketName(), fileName, file.getInputStream()));
            // 检查返回值
            String etag = putObjectResult.getETag(); // 获取ETag

            // 根据返回值进行相应处理
            if (etag != null && !etag.isEmpty()) {
                // 文件上传成功
                logger.info("upload | 文件上传成功，ETag: " + etag);
                String url = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
                return "{\"success\": true, \"url\": \"" + url + "\"}";
            } else {
                // 文件上传失败
                logger.error("upload | 文件上传失败");
                return "{\"success\": false, \"message\": \"上传失败\"}";
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "{\"success\": false, \"message\": \"上传失败\"}";
        } finally {
            ossClient.shutdown();
        }
    }

    @PostMapping("/upload_new")
    public String upload(@RequestParam("files") List<MultipartFile> files) {
        if (files == null || files.isEmpty()) {
            logger.error("upload, no files provided");
            return "{\"success\": false, \"message\": \"没有文件上传\"}";
        }

        List<String> urls = new ArrayList<>();
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );

        try {
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    logger.error("upload, one of the files is empty");
                    return "{\"success\": false, \"message\": \"存在空文件\"}";
                }

                String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();

                PutObjectResult putObjectResult = ossClient.putObject(new PutObjectRequest(ossConfig.getBucketName(), fileName, file.getInputStream()));
                String etag = putObjectResult.getETag(); // 获取ETag

                if (etag != null && !etag.isEmpty()) {
                    // 文件上传成功
                    logger.info("upload | 文件上传成功，ETag: " + etag);
                    String url = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
                    urls.add(url);
                } else {
                    // 文件上传失败
                    logger.error("upload | 文件上传失败");
                    return "{\"success\": false, \"message\": \"上传失败\"}";
                }
            }

            // 返回所有文件的URL
           // return "{\"success\": true, \"urls\": " + urls.toString() + "}";

            // 返回所有文件的URL
            Gson gson = new Gson();
            return gson.toJson(Map.of("success", true, "url", String.join(",", urls)));
        } catch (IOException e) {
            e.printStackTrace();
            return "{\"success\": false, \"message\": \"上传失败\"}";
        } finally {
            ossClient.shutdown();
        }
    }
}
